<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24 0024
 * Time: 下午 2:28
 */
namespace app\api\service;



use app\common\model\User as UserModel;
use app\common\Helper;
use app\lib\exception\WeChatException;
use think\Exception;

class UserToken extends Token{
    protected $code;
    protected $wxLoginUrl;
    protected $wxAppID;
    protected $wxAppSecret;
    function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->wxLoginUrl = sprintf(config('wx.login_url'), $this->wxAppID, $this->wxAppSecret, $this->code);
    }

    public function get(){
        $wxResult = json_decode(Helper::curlGet($this->wxLoginUrl),true);
        if(empty($wxResult)){
            throw new Exception("获取session_key及openID异常，微信内部错误");
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail){
                $this->processLoginError($wxResult);
            }else{
                return $this->grantToken($wxResult);
            }
        }

    }

    private function grantToken($wxResult){
       $openid = $wxResult['openid'];
       $user = UserModel::getByOpenID($openid);
       if(!$user){
           $uid = $this->newUser($openid);
           $user = UserModel::get($uid);
       }
       $data['session_key'] = $wxResult['session_key'];
       $data['user'] = $user;
       return $data;
    }

    private function newUser($openid){

        $user = UserModel::create([
            'id' => Helper::getUUID22(),
            'openId' => $openid

        ]);
        return $user->id;
    }


    private function processLoginError($wxResult){
        throw new WeChatException([
            'msg' => $wxResult['errmsg'],
            'errorCode' => $wxResult['errcode']
        ]);
    }
}
